//
//  EmoticonViewController.swift
//  表情键盘
//
//  Created by apple on 15/7/8.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit

//collectiview的可重用表示符
private let LLEmoticonKeyboardIdentifier = "LLEmoticonKeyboardIdentifier"
class EmoticonViewController: UIViewController {
    
    //定义一个闭包
    var didSelectedEmoticonCallBack:(emoticon:Emoticon)->()
    init(didSelectedEmoticon:(emoticon:Emoticon)->()){
        didSelectedEmoticonCallBack = didSelectedEmoticon
        
        super.init(nibName: nil, bundle: nil)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //选中toolBar按钮方法
    func selectItem(item:UIBarButtonItem) {
        print(item.tag)
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }

    override func loadView() {
        super.loadView()
        collectionView.backgroundColor = UIColor.lightGrayColor()
        prepareUI()
        
    }
    private func prepareUI(){
    //准备toolbar和uicollectionView
        view.addSubview(toolBar)
        view.addSubview(collectionView)
        
        //toolBar和collectionview的自动布局
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        
        var cons = [NSLayoutConstraint]()
        let viewDic = ["collectionView":collectionView, "toolBar":toolBar]
        
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|[collectionView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDic)
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|[toolBar]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDic)
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-0-[toolBar(44)]-0-|", options:NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDic)

        view.addConstraints(cons)
        
        prepareToolBar()
        prepareCollectionView()
     
    }
    //设置collection界面
    private func prepareCollectionView(){
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.pagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
        
        collectionView.registerClass(EmoticonCell.self, forCellWithReuseIdentifier: LLEmoticonKeyboardIdentifier)
        
    }
    
    //设置toolBar界面
    private func prepareToolBar(){
        var items = [UIBarButtonItem]()
        var index = 0
        for s in packages{
        let item = UIBarButtonItem(title: s.groupName, style: UIBarButtonItemStyle.Plain, target: self, action: "selectItem:")
            
            item.tag = index
            index++
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
    
        toolBar.items = items
    }
    //MARK:-----懒加载控件
    
    private lazy var toolBar = UIToolbar()
    private lazy var collectionView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout:EmoticonLayout())
    
    //私有分类
    private class EmoticonLayout: UICollectionViewFlowLayout{
        private override func prepareLayout() {
            super.prepareLayout()
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            scrollDirection = UICollectionViewScrollDirection.Horizontal
            let s = collectionView!.bounds.width / 7
            itemSize = CGSize(width: s, height: s)
            
            let y = (collectionView!.bounds.height - 3 * s) * 0.45
            sectionInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
        }
    }
    
    /// 表情分组数据
    private lazy var packages: [EmoticonPackage] = EmoticonPackage.packages()
}


//EmoticonViewController的扩展
extension EmoticonViewController:UICollectionViewDataSource,UICollectionViewDelegate{
//cell的数据源方法
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LLEmoticonKeyboardIdentifier, forIndexPath: indexPath) as! EmoticonCell
//        cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.yellowColor() : UIColor.blackColor()
        
        cell.emoticon = packages[indexPath.section].emoticons![indexPath.item]

        return cell
    }
    //代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //TODO:=------代理方法
        let emoticon = packages[indexPath.section].emoticons![indexPath.item]
        // 判断表情符号是否有效
        if emoticon.chs != nil || emoticon.emoji != nil {
            emoticon.times++
            // 将表情添加到 `最近的` emoticons 数组
            packages[0].addFavoriteEmoticon(emoticon)
        }
        didSelectedEmoticonCallBack(emoticon: emoticon)
        
    }
    
}

//自定义cell
private class EmoticonCell: UICollectionViewCell{

    
    var emoticon:Emoticon? {
        didSet{
            // 设置图片 - 使用 path 只需要计算一次！
            if let path = emoticon?.imagePath {
                emoticonButton.setImage(UIImage(contentsOfFile: path), forState: UIControlState.Normal)
            } else {
                // 防止 cell 的重用
                emoticonButton.setImage(nil, forState: UIControlState.Normal)
            }
            // 设置 emoji - 直接过滤调用 cell 重用的问题
            emoticonButton.setTitle(emoticon!.emoji ?? "", forState: UIControlState.Normal)
            
            if emoticon!.removeButton {
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
                
            }

        }
    
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
//        添加按钮并且布局
        addSubview(emoticonButton)
        emoticonButton.frame = CGRectInset(bounds, 4, 4)
        emoticonButton.backgroundColor = UIColor.whiteColor()
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        emoticonButton.userInteractionEnabled = false
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //cell里控件的懒加载
    private lazy var emoticonButton = UIButton()
}
